package org.gokeep.communication.demo.p2p;

import lombok.extern.slf4j.Slf4j;
import org.gokeep.common.document.User;
import org.gokeep.communication.demo.TestData;
import org.gokeep.communication.message.MessageBuilder;
import org.gokeep.communication.proto.ChatProto;
import org.gokeep.communication.proto.ChatRequestProto;
import org.gokeep.communication.proto.CommandProto;
import org.gokeep.communication.proto.MessageProto;
import org.smartboot.socket.transport.AioSession;

import java.util.Scanner;

/**
 * 模拟客户端-B
 */
@Slf4j
public class ClientB {
    public static final String SENDER_USERNAME = "shenmiao";

    public static final String RECEIVER_USERNAME = "xuning";

    public static void main(String[] args) {

        User sender = TestData.getUserByName(SENDER_USERNAME);
        User receiver = TestData.getUserByName(RECEIVER_USERNAME);
        String senderToken = TestData.getToken(SENDER_USERNAME);

        MessageClient client = MessageClient.builder();
        // 建立连接
        AioSession session = client.start();
        client.connection(session, senderToken);

        // 输入
        Scanner scanner = new Scanner(System.in);
        System.out.print("回复" + receiver.getNickname() + ":");
        while (!scanner.equals("quit")) {
            String content = scanner.next();
            MessageProto.Message.Builder messageBuilder = MessageBuilder.builder().initMessageBuilder(CommandProto.CommandEnum.CHAT_REQUEST, senderToken);
            ChatRequestProto.ChatRequest.Builder builder = ChatRequestProto.ChatRequest.newBuilder();
            ChatProto.Chat.Builder clientChatMessageBuilder = ChatProto.Chat.newBuilder().setFrom(sender.getUserId())
                    .setTo(receiver.getUserId())
                    .setContent(content);
            builder.setChat(clientChatMessageBuilder);
            messageBuilder.setToken(senderToken);
            messageBuilder.setData(builder.build().toByteString());
            client.send(session, messageBuilder.build());
        }
    }
}
